package com.qmo.edu.moudle.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.qmo.edu.R;
import com.qmo.edu.base.BaseMvpActivity;
import com.qmo.edu.moudle.activity.MainActivity;
import com.qmo.edu.moudle.bean.LoginBean;
import com.qmo.edu.mvp.factroy.CreatePresenterAnnotation;
import com.qmo.edu.mvp.presenter.LoginPresenter;
import com.qmo.edu.mvp.view.LoginView;
import com.qmo.edu.utils.ActivityUtils;
import com.qmo.edu.utils.FunctionUtils;
import com.qmo.edu.utils.SPUtils;
import com.tencent.bugly.beta.Beta;

import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import me.jessyan.autosize.utils.LogUtils;

/**
 * Created by ${} on 2019/6/2/002.
 *
 * @author cyx
 */
@CreatePresenterAnnotation(LoginPresenter.class)
public class LoginActivity extends BaseMvpActivity<LoginView, LoginPresenter> implements LoginView {


    @BindView(R.id.edit_phone)
    EditText mEditPhone;
    @BindView(R.id.edit_password)
    EditText mEditPassword;
    @BindView(R.id.tv_zhuce)
    TextView mTvZhuce;
    @BindView(R.id.wangji_mima)
    TextView mWangjiMima;
    @BindView(R.id.tv_login)
    TextView mTvLogin;
    @BindView(R.id.iv_eye)
    ImageView mIvEye;
    @BindView(R.id.iv_renl)
    ImageView mIvRenl;
    @BindView(R.id.tv_shez)
    TextView mTvShez;
    @BindView(R.id.tv_lianxwm)
    TextView mTvLianxwm;
    private String mTel;
    private String mPwd;
    private Boolean mIsLogin;
    private Boolean mIsOpen;


    @Override
    protected void onResume() {
        super.onResume();


        mIsLogin = (Boolean) SPUtils.get(LoginActivity.this, "isLogin", false);
        if (mIsLogin) {
            ActivityUtils.startActivity(LoginActivity.this, com.qmo.edu.moudle.activity.MainActivity.class);
        }
        if (SPUtils.get(LoginActivity.this, "userName", "") != null) {

            mEditPhone.setText((String) SPUtils.get(LoginActivity.this, "userName", ""));
        }
        if (SPUtils.get(LoginActivity.this, "password", "") != null) {
            mEditPassword.setText((String) SPUtils.get(LoginActivity.this, "password", ""));
        }

        mIsOpen = false;
        mIvEye.setImageResource(R.mipmap.ic_close);
        //从密码可见模式变为密码不可见模式
        mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set alias in handler";
                    Log.e("awj", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
//                    Toast.makeText(LoginActivity.this, "成功", Toast.LENGTH_SHORT).show();
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.e("awj", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("awj  default", logs);
                    break;
            }
//            Toast.makeText(LoginActivity.this, "log=" + logs, Toast.LENGTH_SHORT).show();
        }
    };

    private static final int MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(getApplication(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    Log.e("awj", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    break;
                default:
                    Log.e("awj", "Unhandled msg - " + msg.what);
                    break;
            }
        }
    };

    @Override
    public int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        Beta.autoCheckUpgrade = true;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @OnClick({R.id.tv_login, R.id.tv_zhuce, R.id.wangji_mima, R.id.iv_eye, R.id.iv_renl, R.id.tv_shez, R.id.tv_lianxwm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
//                if (checkParams()) {
//                    getMvpPresenter().login(mEditPhone.getText().toString().trim(), mEditPassword.getText().toString().trim());
//
//                }


                ActivityUtils.startActivity(LoginActivity.this, com.qmo.edu.moudle.activity.MainActivity.class);

                break;

            case R.id.wangji_mima:
                alertShow2();
                break;

            case R.id.iv_renl:
                break;
            case R.id.tv_shez:

                break;
            case R.id.tv_lianxwm:
                break;
            case R.id.iv_eye:

                if (mIsOpen) {
                    mIvEye.setImageResource(R.mipmap.ic_close);
                    mIsOpen = false;
                    //从密码可见模式变为密码不可见模式
                    mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {

                    //从密码不可见模式变为密码可见模式
                    mEditPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mIvEye.setImageResource(R.mipmap.ic_open);
                    mIsOpen = true;

                }


                break;
        }
    }

    public void alertShow2() {

        new AlertView("系统提示", "\n请联系系统管理员进行重置密码\n", null, null, new String[]{"确定"}, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {


            }
        }).show();
    }

    private Boolean checkParams() {
        mTel = mEditPhone.getText().toString().trim();
        mPwd = mEditPassword.getText().toString().trim();
        if (TextUtils.isEmpty(mTel) || TextUtils.isEmpty(mPwd)) {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        FunctionUtils.fixInputMethodManagerLeak(LoginActivity.this);
    }


    @Override
    public void onLogin(LoginBean response) {



        if(response.getCode() == 200){

        SPUtils.put(LoginActivity.this, "token", response.getToken());
        SPUtils.put(LoginActivity.this, "returnUrl", response.getReturnUrl());
//        SPUtils.put(LoginActivity.this, "userId", response.getUserId());
//        SPUtils.put(LoginActivity.this, "Admin", response.getAdmin());
        ActivityUtils.startActivity(LoginActivity.this, MainActivity.class);
//        SPUtils.put(LoginActivity.this, "isLogin", true);
//        SPUtils.put(LoginActivity.this, "userName", mEditPhone.getText().toString().trim());
//        SPUtils.put(LoginActivity.this, "password", mEditPassword.getText().toString().trim());
        finish();
        }else {

        Toast.makeText(LoginActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onError(String errorMsg) {
        LogUtils.e("===============1=" + errorMsg);
        Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
        hideLoading();
    }


}
